<template>
  <div class="setting-container">
    <!-- 提供了一些默认的内边距 padding -->
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName">
          <!-- RBAC: role based access control -->
          <el-tab-pane label="角色管理" name="role">
            <el-button type="primary" size="small" @click="showDialog = true">+ 新增角色</el-button>

            <el-table style="margin: 10px 0" :data="list">
              <el-table-column label="序号" type="index" :index="indexMethod" width="80" />
              <el-table-column label="角色名称" prop="name" width="150" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <!-- el-table组件内部帮我们 v-for 遍历渲染 -->
                <!--
                  组件内部一定有以下代码
                  <slot name="default"></slot>
                 -->
                <!--
                   作用域插槽: 就是在插槽内部绑了数据 传递给我们使用 => 基本语法

                   <slot name="default" :row="xxx" :column="xxx" :$index="xxx"></slot>
                   { row: xxx, column: xxx, $index: xxx } => obj

                   row: 每一行的数据
                   column 列的相关信息 几乎不用
                   $index 索引 从0开始
                  -->
                <template #default="{ row }">
                  <!-- <p>{{ row.id }}</p> -->
                  <el-button size="small" type="success" @click="assign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="edit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!--
              @size-change="handleSizeChange" 点选每页条数 就会触发这个函数
              @current-change="handleCurrentChange"  页码变化时, 就会触发这个函数

              current-page 当前页
              page-sizes 让用户去选择每页多少条
              page-size 现在用户的每页条数
              layout 布局控件
              total 总数
            -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1,2,3,4,5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

      </el-card>

      <!--
        :model="" :rules=""
        prop
        v-model
       -->
      <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button type="primary" @click="clickSubmit">确认</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </template>

      </el-dialog>

      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">

        <!--
          show-checkbox 添加节点前的复选框
          check-strictly 取消父子节点的全选关联
          default-expand-all 默认展开所有节点
          node-key 指定每个节点唯一标识
         -->
        <el-tree
          ref="tree"
          show-checkbox
          check-strictly
          default-expand-all
          node-key="id"
          :data="permissionList"
          :props="{ label: 'name' }"
        />

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="clickAssignSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqDelRole, reqAddRole, reqGetRoleDetail, reqUpdateRole } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
import { reqAssignPermission } from '@/api/setting'
// import { reqGetRoleDetail } from '@/api/setting'
export default {
  name: 'Settings',
  data() {
    return {
      showAssignDialog: false,
      activeName: 'role',
      list: [],
      page: 1,
      pagesize: 2,
      total: 0,
      loading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }
        ]
      },
      permissionList: [],
      roleId: '' // 角色id
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyById()
  },
  methods: {
    closeAssignDialog() {
      this.showAssignDialog = false
      // 关闭时 希望清空所有勾选项
      this.$refs.tree.setCheckedKeys([])
    },
    async assign(id) {
      this.showAssignDialog = true
      this.roleId = id
      console.log(id)
      const { data } = await reqGetPermissionList()
      // console.log(res)
      // 一级权限的pid==='0'
      const result = transListToTree(data, '0')
      this.permissionList = result

      // 发请求 获取角色详情
      const { data: { permIds }} = await reqGetRoleDetail(id)
      // console.log(res)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    async clickAssignSubmit() {
      // 获取勾选节点
      // console.log()
      const permIds = this.$refs.tree.getCheckedKeys()

      const res = await reqAssignPermission(this.roleId, permIds)
      console.log(res)
      this.$message.success('分配权限成功')
      this.closeAssignDialog()
    },
    async getCompanyById() {
      // const res = await reqGetCompanyById(this.$store.state.user.userInfo.companyId)
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      // console.log(res)
      this.companyForm = data
    },
    // 拿着当前最新的页面, 每页条数 进行请求  新数据
    async getRoleList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      // console.log(res)
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 更新每页条数
      this.pagesize = val

      // 规范  只要是每页条数发生变化, 回到第一页 !!!
      this.page = 1

      // 发请求获取新数据
      this.getRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    },
    indexMethod(index) {
      // index 行号 从0开始   0 1 2 3
      // return index + 1 + 前面一共有多少条数据
      return index + 1 + this.pagesize * (this.page - 1)
    },
    del(id) {
      console.log(id, 888)

      // console.log(res)
      // 高危操作 删除
      // 1.确认框
      this.$confirm('你确定删除么?该操作不可逆', '温馨提示').then(async() => {
        const res = await reqDelRole(id)
        console.log(res)
        this.$message.success('删除角色成功')

        // 如果我发现 你是最后最后一条数据 list.length === 1  回到上一页
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }

        this.getRoleList()
      }).catch(() => {
        console.log('取消')
      })
    },
    async edit(id) {
      console.log(id, 777)
      const { data } = await reqGetRoleDetail(id)
      // console.log(res)
      // 给form 赋值 (data => {description: xxx, id: xxx, name: xxx, permIds: xxxx})
      this.form = data
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
      // 重置表单(数据+提示)
      this.$refs.form.resetFields()
      // 为以后做编辑考虑, 将来重置是不会重置表单之外的数据
      this.form = {
        name: '',
        description: ''
      }
    },
    clickSubmit() {
      this.$refs.form.validate(async(flag) => {
        if (!flag) return
        console.log('可以发请求了')
        if (this.form.id) {
          // 编辑
          const res = await reqUpdateRole(this.form)
          console.log(res)
          this.$message.success('编辑角色成功')
        } else {
          // 添加
          const res = await reqAddRole(this.form)
          console.log(res)
          this.$message.success('新增角色成功')
        }

        this.showDialog = false

        this.getRoleList()
      })
    }
  }
}
</script>

<style>

</style>
